<template>
  <div class="create-post">
    <BlogCoverPreview v-show="this.$store.state.blogPhotoPreview"/>
    <Loading v-show="loading" />
    <div class="container">
      <div :class="{invisible: !error}" class="err-message">
        <p><span>Error:</span>{{ this.errorMsg}}</p>
      </div>
      <div class="blog-info">
        <input type="text" placeholder="输入文章标题" maxlength="20" v-model="blogTitle">
        <div class="upload-file">
          <label for="blog-photo">上传图片</label>
          <input type="file" ref="blogPhoto" id="blog-photo" @change="fileChange" accept="image/gif,image/jpg,image/jpeg,image/bmp,image/png, .png, .jpg, .jpeg">
          <button class="preview" @click="openPreview" :class="{ 'button-inactive': !this.$store.state.blogPhotoFileURL }">
            查看图片
          </button>
          <span>文件选择：{{ this.$store.state.blogPhotoName }}</span>
        </div>
      </div>
      <div class="editor">
        <vue-editor  v-model="blogHTML" useCustomImageHandler @image-added="handleImageAdded"/>
      </div>
      <div class="blog-actions">
        <button @click="uploadBlog" >发布文章</button>
        <router-link class="router-button" :to="{ name: 'BlogPreview' }">发布预览</router-link>
      </div>
    </div>
  </div>
</template>

<script>
import BlogCoverPreview from "@/components/BlogCoverPreview"
import Loading from "../components/Loading"
import {uploadImgToBase64} from '@/utils/uploadImgToBase64'
import { createPost } from '@/api/article'
import { sendPhoto, articlePhoto } from '@/api/article'
import Quill from "quill"
window.Quill = Quill;
const ImageResize = require("quill-image-resize-module").default;
Quill.register("modules/imageResize", ImageResize);
export default {
  name:'CreatePost',
  components: {
    BlogCoverPreview,
    Loading,
  },
  data(){
    return {
      file: null,
      error: null,
      errorMsg: null,
      loading: null,
      editorSettings: {
        modules: {
          imageResize: {}
        }
      },
      Base64Img: ''
    }
  },
  watch: {
    $route() {
      this.closeInfo()
    }
  },
  methods:{
    handleImageAdded:async function(file, Editor, cursorLocation, resetUploader) {
      // An example of using FormData
      // NOTE: Your key could be different such as:
      // formData.append('file', file)
      let formData = new FormData();
      formData.append("image", file);
      await articlePhoto(formData)
        .then(result => {
          const url = result.data.url; // Get url from response
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        })
        .catch(err => {
          console.log(err);
        });
    },
    async fileChange() {
      this.file = this.$refs.blogPhoto.files[0];

      const fileName = this.file.name
      //  图片转64
      const response = await uploadImgToBase64(this.file)
      this.Base64Img  = response.result.replace(/.*;base64,/, '')
      // this.$store.commit('setBase64Img',filePromises)
      this.$store.commit('fileNameChange',fileName)
      this.$store.commit('createFileURL',URL.createObjectURL(this.file))
    },
    openPreview(){
      this.$store.commit("openPhotoPreview");
    },
    async uploadBlog() {
      this.loading = true
      // 这个if判断 this.blogTitle是否为空，his.blogHTML.length是否填写内容
      if (this.blogTitle.length !== 0 && this.blogHTML.length !== 0) {
        if (this.Base64Img) {
            if(this.Base64Img.length < 5242880){
              await sendPhoto({
                base64Img:this.Base64Img,
                name: this.file.name,
              })

              let articleInfo = {
                article : {
                  "title": this.blogTitle,
                  "author": this.$store.state.user.username,
                  "body": this.blogHTML,
                  // "image": 'http://120.55.13.230:3000/blog-express/static/postView/'+this.file.name
                  "image": 'http://127.0.0.1:3000/static/postView/'+this.file.name
                }
              }
              await createPost(articleInfo)
              await this.$store.dispatch('getPost')
              this.$store.commit('setBlogState','')
              this.loading = false
              this.$router.push({name:"Blogs"})
              return;
            }
            this.loading = false
            this.error = true;
            this.errorMsg = "上传图片不能超过5M!，请重新选择"
            return;
        }
        this.loading = false
        this.error = true;
        this.errorMsg = "请上传图片";
        setTimeout(() => {
          this.error = false;
        }, 5000);
        return;
        }
      this.error = true;
      this.errorMsg = "请填写标题！";
      setTimeout(() => {
        this.error = false;
      }, 5000);
      this.loading = false
      return;
    },
  },
  computed:{
    profileId() {
      return this.$store.state.profileId;
    },
    blogCoverPhotoName() {
      return this.$store.state.blogPhotoName
    },
    blogTitle: {
      get() {
        return this.$store.state.blogTitle
      },
      set(value){
        this.$store.commit('updateBlogTitle',value)
      }
    },
    blogHTML: {
      get() {
        return this.$store.state.blogHTML
      },
      set(value){
        this.$store.commit('newBlogPost',value)
      }
    }
  }
}
</script>

<style lang="scss">
.create-post {
  position: relative;
  height: 100%;
  button {
    margin-top: 0;
  }
  .router-button {
    text-decoration: none;
    color: #fff;
  }
  label,
  button,
  .router-button {
    transition: 0.5s ease-in-out all;
    align-self: center;
    font-size: 14px;
    cursor: pointer;
    border-radius: 20px;
    padding: 12px 24px;
    color: #fff;
    background-color: #303030;
    text-decoration: none;
    &:hover {
      background-color: rgba(48, 48, 48, 0.7);
    }
  }
  .container {
    position: relative;
    height: 100%;
    padding: 10px 25px 60px;
  }
  // error styling
  .invisible {
    opacity: 0 !important;
  }
  .err-message {
    width: 100%;
    padding: 12px;
    border-radius: 8px;
    color: #fff;
    margin-bottom: 10px;
    background-color: #303030;
    opacity: 1;
    transition: 0.5s ease all;
    p {
      font-size: 14px;
    }
    span {
      font-weight: 600;
    }
  }
  .blog-info {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 32px;
    input:nth-child(1) {
      min-width: 300px;
    }
    input {
      transition: 0.5s ease-in-out all;
      padding: 10px 4px;
      border: none;
      border-bottom: 1px solid #303030;
      margin-right: 16px;
      &:focus {
        outline: none;
        box-shadow: 0 1px 0 0 #303030;
      }
    }
    .upload-file {
      flex: 1;
      padding-top: 10px;
      position: relative;
      display: flex;
      input {
        display: none;
      }
      .preview {
        margin-left: 16px;
        text-transform: initial;
      }
      span {
        font-size: 12px;
        margin-left: 16px;
        align-self: center;
      }
    }
  }
  .editor {
    height: 60vh;
    display: flex;
    flex-direction: column;
    .quillWrapper {
      position: relative;
      display: flex;
      flex-direction: column;
      height: 100%;
    }
    .ql-container {
      display: flex;
      flex-direction: column;
      height: 100%;
      overflow: scroll;
    }
    .ql-editor {
      padding: 20px 16px 30px;
    }
  }
  .blog-actions {
    margin-top: 32px;
    button {
      margin-right: 16px;
    }
  }
}
</style>